package com.roomio.core.security.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.roomio.core.security.model.User;
import com.roomio.core.security.model.UserNotRegisteredException;
import com.roomio.core.security.service.UserInfoService;
import com.roomio.dao.UserInfoDAO;

/** Demo UserService IMplementation to keep all "registered" users in memory
 * 
 * @author Shailendra
 *
 */
public class DatabaseUserDetailsService implements UserDetailsService {
	
	@Autowired
	UserInfoService userInfoService;
	
	@Autowired
	UserInfoDAO userInfoDao;
	/** Since we are using only OpenID authentication - username is openId account
	 * 
	 */
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException,UserNotRegisteredException {
		UserDetails userDetail =userInfoService.findByIdentityUrl(username);
		if(userDetail  == null) {
			 User user= userInfoDao.findUserByEmail(username);
			if (user == null) {
				throw new UsernameNotFoundException("Cannot find user " + username);
			}else{
				if(!user.isEnabled())
				throw new UserNotRegisteredException(user, "User not registered to application");
			}
		}
		
		return userDetail;
	}
	
	/** Method allowed to add new userDetails */
	public void addUser(User userDetails) {
		userInfoService.persist(userDetails);
	}
	/** Method allowed to add new userDetails */
	public void updateUser(User userDetails) {
		userInfoService.merge(userDetails);
	}

}
